package com.anquing.ssodemo.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
 * 网络请求工具类
 */
public class HttpClientUtil {

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String sendGet(String url){
        CloseableHttpClient httpClient =null;
        try {
            httpClient = HttpClients.custom().build();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            String result = null;
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                result = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
                return result;
            }
        }catch (Exception e){
            log.debug("send Get request exception:{}",e.getMessage());
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
        return null;
    }

    /**
     * httpClient post 有超时设置
     * @param url
     * @param params
     * @return
     */
    public static String sendPost(String url, Map<String,Object> params){

        //超时设置1：新建一个RequestConfig
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(20000)//返回超时设置，单位毫秒
                .setConnectTimeout(20000)//连接超时设置，单位毫秒
                .setConnectionRequestTimeout(5000)//不清楚
                .build();

        CloseableHttpClient httpClient =null;
        try {
            //超时设置2：将超时设置为客户端级别，作为所有请求的默认值
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
            httpPost.setConfig(requestConfig);
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            Iterator it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry)it.next();
                formparams.add(new BasicNameValuePair((String)entry.getKey(),(String) entry.getValue()));
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String result = EntityUtils.toString(entity, "UTF-8");
                        return result;
                    }
                }
                return null;
            } finally {
                response.close();
            }
        }catch (Exception e){
            log.debug("send Get request exception:{}",e.getMessage());
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
        return null;
    }

//    public static String sendPost(String url, Set<Cookie> cookiesSet, Map<String, Object> params){
//        CloseableHttpClient httpClient =null;
//        try {
//
//            CookieStore cookieStore = new BasicCookieStore();
//            Iterator<Cookie> iterator = cookiesSet.iterator();
//            while (iterator.hasNext()){
//                Cookie next = iterator.next();
//                BasicClientCookie cookie = new BasicClientCookie(next.getName(), next.getValue());
//                cookie.setDomain(next.getDomain());
//                cookie.setPath(next.getPath());
//                cookieStore.addCookie(cookie);
//            }
//
//            httpClient = HttpClients.custom()
//                    .setDefaultCookieStore(cookieStore)
//                    .build();
//
//            HttpPost httpPost = new HttpPost(url);
//
//
//            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
//            Iterator it = params.entrySet().iterator();
//            while (it.hasNext()) {
//                Map.Entry entry = (Map.Entry)it.next();
//                formparams.add(new BasicNameValuePair((String)entry.getKey(),(String) entry.getValue()));
//            }
//            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
//            httpPost.setEntity(urlEncodedFormEntity);
//            CloseableHttpResponse response = httpClient.execute(httpPost);
//            try {
//                if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
//                    HttpEntity entity = response.getEntity();
//                    if (entity != null) {
//                        String result = EntityUtils.toString(entity, "UTF-8");
//                        return result;
//                    }
//                }
//                log.debug("status code:{}",response.getStatusLine().getStatusCode());
//                return null;
//            } finally {
//                response.close();
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            log.debug("send Get request exception:{}",e.getMessage());
//        }finally {
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//            }
//        }
//        return null;
//    }

    /**
     * unicode编码转UTF-8
     * @param theString
     * @return String
     */
    public String unicodeToUtf8(String theString) {
        char aChar;
        int len = theString.length();
        StringBuffer outBuffer = new StringBuffer(len);
        for (int x = 0; x < len;) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException(
                                        "Malformed   \\uxxxx   encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't'){
                        aChar = '\t';
                    }
                    else if (aChar == 'r'){
                        aChar = '\r';
                    }
                    else if (aChar == 'n'){
                        aChar = '\n';
                    }
                    else if (aChar == 'f'){
                        aChar = '\f';
                    }
                    outBuffer.append(aChar);
                }
            } else{
                outBuffer.append(aChar);
            }

        }
        return outBuffer.toString();
    }

    /**
     * 获取一个网络图片
     * @param url
     */
    public static byte[] getImg(String url){
        CloseableHttpClient httpClient =null;
        InputStream inStream=null;
        try {
            httpClient = HttpClients.custom().build();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            String result = null;
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                inStream = httpResponse.getEntity().getContent();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while( (len=inStream.read(buffer)) != -1 ){
                    outStream.write(buffer, 0, len);
                }
                inStream.close();
                byte[] btImg = outStream.toByteArray();
                return btImg;
            }
        }catch (Exception e){
            log.debug("send Get Img request exception:{}",e.getMessage());
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
        return null;
    }


    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("key","value");
        String result = sendPost("http://localhost/http/test", map);
        System.out.println("client:"+result);
    }

}
